package cn.portx.report;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.bstek.bdf3.dorado.jpa.JpaUtil;

import cn.portx.entity.ExpenseItem;
import cn.portx.entity.Order;
import cn.portx.entity.OrderExpense;
import cn.portx.entity.OrderSendReceive;
import cn.portx.view.ExportPR;

//@Component
public class ProfitsMxDataSource {

	@Autowired
	private ExportPR exportPR;

	public List<Map<String, Object>> loadReportData(String dsName, String datasetName, Map<String, Object> parameters) {
		List<String> orderIds = (List<String>) parameters.get("orderIds");
		List<Order> list = exportPR.loadOrders(orderIds.toArray(new String[] {}));
		List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
		for (Order order : list) {
			Map<String, Object> map = new HashMap<String, Object>();
			List<OrderSendReceive> osrList = JpaUtil.linq(OrderSendReceive.class).equal("orderId", order.getId()).asc("type").list();
			List<OrderExpense> yingshouList = JpaUtil.linq(OrderExpense.class).collect(ExpenseItem.class, "expenseItemId").equal("orderId", order.getId()).equal("type", "0")
					.list();//应收
			List<OrderExpense> yingfuList = JpaUtil.linq(OrderExpense.class).collect(ExpenseItem.class, "expenseItemId").equal("orderId", order.getId()).equal("type", "1").list();//应付
			List<OrderExpense> chengbenList = JpaUtil.linq(OrderExpense.class).collect(ExpenseItem.class, "expenseItemId").equal("orderId", order.getId()).equal("type", "0")
					.list();//成本
			map.put("orderNo", order.getOrderNo());
			map.put("orderDate", order.getOrderDate());
			map.put("customerName", order.getCustomer()==null?null:order.getCustomer().getName());
			map.put("type", order.getType());
			map.put("zxdd", this.getZxdd(osrList));
			map.put("boxType", order.getBoxType());
			map.put("quantity", order.getQuantity());
			map.put("cntNo", order.getCntNo());
			map.put("zxrq", order.getZxrq());
			map.put("shippingCompanyName", order.getShippingCompany()==null?null:order.getShippingCompany().getName());
			map.put("vesselName", order.getVessel()==null?null:order.getVessel().getName());
			map.put("voyage", order.getVoyage());

			double yingshouheji = 0;//应收合计
			for (OrderExpense oe : yingshouList) {
				yingshouheji += oe.getExpenseVal();
				map.put("expenseItemName", oe.getExpenseItem().getName());
			}
			map.put("yingshouheji", yingshouheji);
			
		}
		return null;
	}

	/**
	 * 获取装卸地点
	 * 
	 * @param osrList
	 * @return
	 */
	private String getZxdd(List<OrderSendReceive> osrList) {
		StringBuilder sb = new StringBuilder();
		for (OrderSendReceive osr : osrList) {
			sb.append(osr.getAddress() + "。");
		}
		return sb.toString();
	}
}
